package com.come4loves.core.utils;

import io.netty.channel.ChannelHandlerContext;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HostUtil {
	private static final Logger LOGGER = LoggerFactory.getLogger(HostUtil.class);
	private static String hostIP = "127.0.0.1";
	static {
		try {
			Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface
					.getNetworkInterfaces();
			InetAddress ip = null;
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
						.nextElement();
				if (netInterface.getName().startsWith("eth")) {
					Enumeration<InetAddress> addresses = netInterface
							.getInetAddresses();
					while (addresses.hasMoreElements()) {
						ip = (InetAddress) addresses.nextElement();
						if (ip != null && ip instanceof Inet4Address) {
							hostIP = ip.getHostAddress();
							LOGGER.info("server host ip: {}", hostIP);
						}
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("{}", e);
		}
	}
	
	public static String getHostIP() {
		return hostIP;
	}
	
	public static String getRomoteIP(ChannelHandlerContext ctx) {
		SocketAddress add = ctx.channel().remoteAddress();
		String remoteIp = null;
		if(add != null) {
			remoteIp = ((InetSocketAddress) add).getAddress().getHostAddress();
		}
		if (StringUtils.isBlank(remoteIp)) { 
			remoteIp = ((InetSocketAddress) ctx.channel().localAddress()).getAddress().getHostAddress();
		}
		return remoteIp;
	}
}
